<template>
    <div>
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" />
            </el-form-item>
            <el-form-item prop="checked">
                <el-checkbox v-model="ruleForm.checked">
                    记住我
                </el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleRegister(ruleFormRef)">
                    注册
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';

const router = useRouter()

const ruleFormRef = ref()

const ruleForm = reactive({
    username: '',
    password: '',
    checked: [],
})

const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 5, message: '输入内容在3到5个字之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 6, message: '输入内容在3到6个字之间', trigger: 'blur' },
    ],
    checked: [
        {
            type: 'array',
            required: true,
            message: '请选择复选框',
            trigger: 'change',
        },
    ],
})

const handleRegister = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('注册按钮');
            axios.post('/api/register', ruleForm).then(res => {
                console.log(res)
                // 如果注册成功就跳转登录页面，并且提示注册成功
                if (res.data.code === 10000 && res.status === 200) {
                    ElMessage({
                        message: res.data.message,
                        type: 'success',
                    })
                    router.push({
                        path: '/login'
                    })
                } else {
                    // 如果失败，就提示失败原因（失败原因接口会返回）
                    ElMessage.error(res.data.message)
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}

</script>